package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.analyse.ParseState;
import com.kdtech.crawler.CrawlHTML;


import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;

/**
 * http://forum.home.news.cn/ 新华论坛
 * @author 小聂
 */
public class NewsBbsAnalyse implements AnalyseNews{

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://forum.home.news.cn/detail/[0-9]+/[0-9]{1,2}.html",
				"http://bbs.home.news.cn/.*/[0-9]{8}.htm"
				};
		//http://forum.home.news.cn/detail/140137022/1.html
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		bbs.setUrl(url);
		String title = null;
		Long date = null;
		String content = null;
		String dateStr = null;
		Document doc = Jsoup.parse(htmltxt);

		if(doc.select("body").text().contains("对不起！发现未知错误[帖子已不存在]")){
			bbs.setUpdateUrl(ParseState.ERR404.toString());
			return bbs;
		}

		title = doc.select("h1 span").text();
		if(StringUtils.isBlank(title)){
			title = doc.select("h2").text();
		}
		dateStr = doc.select("li.fr span").text();
		if(StringUtils.isBlank(dateStr)){
			dateStr = doc.select(".bannerlcon").text();
		}
		content = HtmlCleaner.getContentHtml(url,  doc.select("div#message_"));
		if(StringUtils.isBlank(content)){
			content = HtmlCleaner.getContentHtml(url,  doc.select("div.con"));
		}
		if(StringUtils.isBlank(content)){
			content = HtmlCleaner.getContentHtml(url,  doc.select("div#aContent"));
		}
		//
		if(StringUtils.isBlank(content)){
			
		}
		
		date = DateUtils.matchDate(dateStr);
		bbs.setContent(content);
		bbs.setDate(date);
		bbs.setTitle(title);
		bbs.setType(4);


		String author=doc.select("ul[class='de-xx clear'] li:eq(1) a").text();
		if(StringUtils.isBlank(author)){
			author = JSoupUtils.matchAuthor(doc, "责编：");
		}
		bbs.setAuthor(author);
		/**
		 * 点击数更新
		 */
		bbs.setUpdateUrl(url);
		if(date==null || title==null){
		}
		return bbs;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if (StringUtils.isNotBlank(updateUrl)){
				UrlMeta urlMeta = CrawlHTML.responseToURL(updateUrl);
				return parserHtml(urlMeta);
			}
			return null;
		}
		return null;
	}

	
	
}
